// 资源导入API服务
// REF: API-SHARE189-004@v1.0

import { ShareCode, PaginationInfo, PreviewResult } from './types';
import { apiRequest } from './utils';

export class ImportApiService {
  // 获取分享码列表
  static async getShareList(
    page = 1,
    perPage = 20,
    statusFilter?: string
  ): Promise<{ items: ShareCode[]; pagination: PaginationInfo }> {
    const params = new URLSearchParams({
      page: page.toString(),
      perPage: perPage.toString()
    });
    
    if (statusFilter && statusFilter !== 'all') {
      params.append('status', statusFilter);
    }
    
    const response = await fetch(`/api/share189/list?${params}`, {
      headers: apiRequest.getAuthHeaders()
    });
    
    if (!response.ok) {
      throw new Error('获取分享码列表失败');
    }
    
    const data = await response.json();
    return data.data;
  }

  /**
   * 预览分享码
   */
  static async previewShareCode(shareCode: string, accessCode?: string): Promise<PreviewResult> {
    // 格式验证
    if (!shareCode || shareCode.length < 8) {
      throw new Error('分享码格式无效');
    }

    try {
      const response = await fetch('/api/share189/preview-code', {
        method: 'POST',
        headers: apiRequest.getJsonHeaders(),
        body: JSON.stringify({
          shareCode,
          accessCode: accessCode || ''
        })
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.message || '预览分享码失败');
      }

      const result = await response.json();
      return result.data;
    } catch (error: any) {
      console.error('预览分享码失败:', error);
      const errorMessage = error.message || '预览分享码失败，请检查分享码是否正确';
      throw new Error(errorMessage);
    }
  }

  // 添加单个分享码
  static async addShareCode(data: {
    shareCode: string;
    accessCode?: string;
    description?: string;
  }): Promise<{ id: number; shareCode: string; message: string }> {
    const response = await fetch('/api/share189/add', {
      method: 'POST',
      headers: apiRequest.getJsonHeaders(),
      body: JSON.stringify(data)
    });
    
    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.message || '添加分享码失败');
    }
    
    const result = await response.json();
    return result.data;
  }

  // 解析文本中的分享码
  static async parseTextForShareCodes(data: {
    text: string;
    extractAccessCodes?: boolean;
  }): Promise<{
    shareCodes: string[];
    accessCodes: string[];
    suggestions: {
      shareCode: string;
      accessCode?: string;
      description: string;
    }[];
  }> {
    // 本地解析文本中的分享码和访问码
    const text = data.text;
    const extractAccessCodes = data.extractAccessCodes !== false;
    
    // 分享码正则表达式
    const shareCodePatterns = [
      // 完整链接格式: https://cloud.189.cn/t/abc123def
      /https?:\/\/cloud\.189\.cn\/t\/([a-zA-Z0-9]+)/g,
      // 分享码格式: 分享码：abc123def 或 分享码:abc123def
      /分享码[：:][\s]*([a-zA-Z0-9]+)/g,
      // 链接格式: 链接: https://cloud.189.cn/t/abc123def
      /链接[：:]?[\s]*https?:\/\/cloud\.189\.cn\/t\/([a-zA-Z0-9]+)/g
    ];
    
    // 访问码正则表达式
    const accessCodePatterns = [
      // 访问码：1234 或 提取码：1234
      /(?:访问码|提取码)[：:][\s]*([a-zA-Z0-9]+)/g,
      // 密码：1234
      /密码[：:][\s]*([a-zA-Z0-9]+)/g
    ];
    
    const shareCodes: string[] = [];
    const accessCodes: string[] = [];
    
    // 提取分享码
    for (const pattern of shareCodePatterns) {
      let match;
      while ((match = pattern.exec(text)) !== null) {
        const shareCode = match[1];
        if (shareCode && shareCode.length >= 8 && !shareCodes.includes(shareCode)) {
          shareCodes.push(shareCode);
        }
      }
    }
    
    // 提取访问码
    if (extractAccessCodes) {
      for (const pattern of accessCodePatterns) {
        let match;
        while ((match = pattern.exec(text)) !== null) {
          const accessCode = match[1];
          if (accessCode && !accessCodes.includes(accessCode)) {
            accessCodes.push(accessCode);
          }
        }
      }
    }
    
    // 生成建议列表
    const suggestions = shareCodes.map((shareCode, index) => {
      // 尝试匹配对应的访问码
      const accessCode = accessCodes[index] || accessCodes[0] || undefined;
      return {
        shareCode,
        accessCode,
        description: `分享码 ${shareCode}${accessCode ? ` (访问码: ${accessCode})` : ''}`
      };
    });
    
    return {
      shareCodes,
      accessCodes,
      suggestions
    };
  }

  // 批量添加分享码
  static async batchAddShareCodes(data: {
    shareCodes: {
      shareCode: string;
      accessCode?: string;
      description?: string;
    }[];
  }): Promise<{
    addedCount: number;
    skippedCount: number;
    errorCount: number;
    errors: string[];
    message: string;
  }> {
    const response = await fetch('/api/share189/batch-add', {
      method: 'POST',
      headers: apiRequest.getJsonHeaders(),
      body: JSON.stringify(data)
    });
    
    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.message || '批量添加分享码失败');
    }
    
    const result = await response.json();
    return result.data;
  }

  // 批量导入分享码（兼容旧接口）
  static async batchImportShareCodes(text: string): Promise<{ addedCount: number }> {
    // 解析文本
    const parseResult = await this.parseTextForShareCodes({
      text,
      extractAccessCodes: true
    });
    
    if (parseResult.suggestions.length === 0) {
      throw new Error('文本中没有发现有效的分享码');
    }
    
    // 批量添加
    const addResult = await this.batchAddShareCodes({
      shareCodes: parseResult.suggestions
    });
    
    return { addedCount: addResult.addedCount };
  }

  // 获取分享码详情
  static async getShareDetail(shareId: number): Promise<ShareCode> {
    const response = await fetch(`/api/share189/${shareId}`, {
      headers: apiRequest.getAuthHeaders()
    });
    
    if (!response.ok) {
      throw new Error('获取分享码详情失败');
    }
    
    const data = await response.json();
    return data.data;
  }

  // 解析分享码
  static async parseShareCode(shareId: number, force: boolean = false, depth: number = 3): Promise<void> {
    const response = await fetch(`/api/share189/${shareId}/parse`, {
      method: 'POST',
      headers: apiRequest.getJsonHeaders(),
      body: JSON.stringify({
        force,
        depth
      })
    });
    
    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.message || '解析分享码失败');
    }
  }

  // 删除分享码
  static async deleteShareCode(shareId: number): Promise<void> {
    const response = await fetch(`/api/share189/${shareId}`, {
      method: 'DELETE',
      headers: apiRequest.getAuthHeaders()
    });
    
    if (!response.ok) {
      throw new Error('删除分享码失败');
    }
  }

  // 导入到虚拟网盘
  static async importToVirtualDisk(
    shareId: number,
    userId: number,
    targetFolderId?: number,
    conflictStrategy: string = 'rename',
    preserveStructure: boolean = true
  ): Promise<any> {
    const response = await fetch(`/api/share189/${shareId}/import`, {
      method: 'POST',
      headers: apiRequest.getJsonHeaders(),
      body: JSON.stringify({ 
        targetFolderId: targetFolderId || null,
        conflictStrategy,
        preserveStructure
      })
    });
    
    if (!response.ok) {
      throw new Error('导入到虚拟网盘失败');
    }
    
    const data = await response.json();
    return data.data;
  }
}

export default ImportApiService;